package moe.bogos.douro.api.common;

import moe.bogos.douro.api.DouroAPI;
import moe.bogos.douro.api.common.capabilities.CapMapProvider;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber(modid = DouroAPI.MODID)
public class CommonEventSubscriber
{
    @SubscribeEvent
    public static void onClonePlayer(PlayerEvent.Clone event)
    {
        if (event.isWasDeath())
        {
            CapMapProvider.get(event.getPlayer()).loadNBTData(CapMapProvider.get(event.getOriginal()).saveNBTData());
            CapMapProvider.get(event.getPlayer()).dataChanged(event.getPlayer());
        }
    }
    
    @SubscribeEvent
    public static void onEntityJoinWorld(EntityJoinWorldEvent event)
    {
        if (event.getEntity() instanceof PlayerEntity && !event.getEntity().getCommandSenderWorld().isClientSide)
        {
            /*TEST CODE*/
            /*Entity entity = new EntitySoulRing(event.getWorld(),100);
            entity.posX = event.getEntity().posX;
            entity.posY = event.getEntity().posY;
            entity.posZ = event.getEntity().posZ;
            event.getWorld().spawnEntity(entity);*/
            /*TEST CODE*/
            
            CapMapProvider.get((PlayerEntity) event.getEntity()).dataChanged((PlayerEntity) event.getEntity());
        }
    }
    
    @SubscribeEvent
    public static void onAttachCapability(AttachCapabilitiesEvent<Entity> event)
    {
        //DouroAPI.LOGGER.info("add capability...");
        ResourceLocation key = new ResourceLocation(DouroAPI.MODID, "soul_map");
        if (event.getObject() instanceof PlayerEntity && !event.getCapabilities().containsKey(key))
            event.addCapability(key, new CapMapProvider());
    }
    
    @SubscribeEvent
    public static void onServerTick(TickEvent.ServerTickEvent event)
    {
        if(event.phase == TickEvent.Phase.END)
            Timer.serverInstance.onTick();
    }
    
    @OnlyIn(Dist.CLIENT)
    @SubscribeEvent
    public static void onClientTick(TickEvent.ClientTickEvent event)
    {
        if(event.phase == TickEvent.Phase.END)
            Timer.clientInstance.onTick();
    }
}
